import type { AxiosRequestConfig, Canceler } from 'axios'

// 用于存储每个请求的识别和取消功能
let pendingMap = new Map<string, Canceler>()

export const getPendingUrl = (config: AxiosRequestConfig) => [config.method, config.url].join('&')

export class AxiosCanceler {
  /**
   * 添加请求
   * @param {object} config
   */
  addPending(config: AxiosRequestConfig) {
    this.removePending(config)
    const url = getPendingUrl(config)
    if (!config.signal) {
      const controller = new AbortController()
      if (!pendingMap.has(url)) {
        pendingMap.set(url, () => {
          controller.abort()
        })
      }
    }
  }

  /**
   * @description 清除所有待处理的请求
   */
  removeAllPending() {
    pendingMap.forEach((cancel) => {
      cancel && typeof cancel === 'function' && cancel()
    })
    pendingMap.clear()
  }

  /**
   * 清除指定等待的请求
   * @param {object} config
   */
  removePending(config: AxiosRequestConfig) {
    const url = getPendingUrl(config)

    if (pendingMap.has(url)) {
      // If there is a current request identifier in pending,
      // the current request needs to be cancelled and removed
      const cancel = pendingMap.get(url)
      cancel && cancel(url)
      pendingMap.delete(url)
    }
  }

  /**
   * @description 重置等待的请求
   */
  reset(): void {
    pendingMap = new Map<string, Canceler>()
  }
}
